using Devtodo.Models;
using Microsoft.Data.Sqlite;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.ObjectModel;
using Windows.Storage;
namespace Devtodo.Pages;

public sealed partial class Update : Page
{
  public Update()
  {
    InitializeComponent();
    LoadProjectList();
  }
  public ObservableCollection<UpdateItem> Items { get; } = [];
  public ObservableCollection<string> ProjectNames { get; set; } = [];
  public ObservableCollection<string> Versions { get; set; } = [];
  int UpdateId { get; set; } = -1;
  async void LoadList()
  {
    Items.Clear();
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    await connection.OpenAsync();
    var selectVersionCmd = new SqliteCommand("SELECT * FROM 'update' WHERE versionid=" + GetVersionId(Version.SelectedValue.ToString()), connection);
    var updateReader = await selectVersionCmd.ExecuteReaderAsync();
    while (await updateReader.ReadAsync())
    {
      Items.Add(new UpdateItem
      {
        Id = updateReader.GetInt32(0),
        VersionId = updateReader.GetInt32(1),
        Type = updateReader.GetString(2),
        Content = updateReader.GetString(3),
        Tip = updateReader.GetString(4),
        Finished = updateReader.GetInt32(5)
      });
    }
    await connection.CloseAsync();
  }
  async void LoadProjectList()
  {
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    await connection.OpenAsync();
    var selectProjectCmd = new SqliteCommand("SELECT name FROM project", connection);
    var projectReader = await selectProjectCmd.ExecuteReaderAsync();
    while (await projectReader.ReadAsync())
    {
      ProjectNames.Add(projectReader.GetString(0));
    }
    await connection.CloseAsync();
    Project.ItemsSource = ProjectNames;
    Project.SelectedItem = ProjectNames[0];
    LoadVersionList();
  }
  async void LoadVersionList()
  {
    Versions.Clear();
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    await connection.OpenAsync();
    var selectVersionCmd = new SqliteCommand("SELECT version FROM version WHERE projectid=" + GetProjectId(Project.SelectedValue.ToString()) + " ORDER BY id DESC", connection);
    var VersionReader = await selectVersionCmd.ExecuteReaderAsync();
    while (await VersionReader.ReadAsync())
    {
      Versions.Add(VersionReader.GetString(0));
    }
    await connection.CloseAsync();
    Version.ItemsSource = Versions;
    Version.SelectedItem = Versions[0];
    LoadList();
  }
  static int GetProjectId(string ProjectName)
  {
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    connection.Open();
    var selectCmd = new SqliteCommand("SELECT id FROM project WHERE name='" + ProjectName + "'", connection);
    var reader = selectCmd.ExecuteReader();
    if (reader.Read())
    {
      var projectId = reader.GetInt32(0);
      connection.Close();
      return projectId;
    }
    connection.Close();
    return -1;
  }
  int GetVersionId(string Version)
  {
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    connection.Open();
    var selectProjectCmd = new SqliteCommand("SELECT id FROM project WHERE name='" + Project.SelectedValue + "'", connection);
    var projectReader = selectProjectCmd.ExecuteReader();
    if (projectReader.Read())
    {
      var projectId = projectReader.GetInt32(0);
      var selectVersionCmd = new SqliteCommand("SELECT id FROM version WHERE projectid=" + projectId + " AND version='" + Version + "'", connection);
      var versionReader = selectVersionCmd.ExecuteReader();
      if (versionReader.Read())
      {
        var versionId = versionReader.GetInt32(0);
        connection.Close();
        return versionId;
      }
    }
    connection.Close();
    return -1;
  }
  void ChangeProject(object sender, SelectionChangedEventArgs args)
  {
    LoadVersionList();
  }
  void ChangeVersion(object sender, SelectionChangedEventArgs args)
  {
    LoadList();
  }
  void Back()
  {
    List.Visibility = Visibility.Visible;
    New.Visibility = Visibility.Collapsed;
    UpdateStackPanel.Visibility = Visibility.Collapsed;
    UpdateId = -1;
    InsertTypeInput.SelectedIndex = 0;
    UpdateTypeInput.SelectedIndex = 0;
    InsertContentInput.Text = "";
    UpdateContentInput.Text = "";
    InsertTipInput.Text = "";
    UpdateTipInput.Text = "";
    LoadList();
  }
  void NavigateToNew(object sender, RoutedEventArgs args)
  {
    List.Visibility = Visibility.Collapsed;
    New.Visibility = Visibility.Visible;
    UpdateStackPanel.Visibility = Visibility.Collapsed;
  }
  void NavigateToUpdate(object sender, RoutedEventArgs args)
  {
    if (sender is Button btn)
    {
      var e = (UpdateItem)btn.Tag;
      UpdateId = e.Id;
      UpdateTypeInput.SelectedValue = e.Type;
      UpdateContentInput.Text = e.Content;
      UpdateTipInput.Text = e.Tip;
    }
    List.Visibility = Visibility.Collapsed;
    New.Visibility = Visibility.Collapsed;
    UpdateStackPanel.Visibility = Visibility.Visible;
  }
  void NavigateBack(object sender, RoutedEventArgs args)
  {
    Back();
  }
  async void NewUpdate(object sender, RoutedEventArgs args)
  {
    try
    {
      if (InsertTypeInput.SelectedValue.ToString().Length == 0) { }
      if (InsertContentInput.Text.Length == 0)
      {
        ContentDialog dialog = new()
        {
          XamlRoot = XamlRoot,
          Title = "提示",
          Content = "请输入内容",
          PrimaryButtonText = "确定",
          DefaultButton = ContentDialogButton.Primary
        };
        await dialog.ShowAsync();
        return;
      }
      var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
      await connection.OpenAsync();
      var incertCmd = new SqliteCommand("INSERT INTO 'update' (versionid, type, content, tip, finished) VALUES (" + GetVersionId(Version.SelectedValue.ToString()) + ",'" + InsertTypeInput.SelectedValue + "','" + InsertContentInput.Text + "','" + InsertTipInput.Text + "',0)", connection);
      await incertCmd.ExecuteNonQueryAsync();
      await connection.CloseAsync();
      ContentDialog successDialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "提示",
        Content = "新增成功",
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await successDialog.ShowAsync();
      Back();
    }
    catch (Exception err)
    {
      ContentDialog dialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "错误",
        Content = err.Message,
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await dialog.ShowAsync();
    }
  }
  async void UpdateUpdate(object sender, RoutedEventArgs args)
  {
    try
    {
      if (UpdateContentInput.Text.Length == 0)
      {
        ContentDialog dialog = new()
        {
          XamlRoot = XamlRoot,
          Title = "提示",
          Content = "请输入内容",
          PrimaryButtonText = "确定",
          DefaultButton = ContentDialogButton.Primary
        };
        await dialog.ShowAsync();
        return;
      }
      var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
      await connection.OpenAsync();
      var updateCmd = new SqliteCommand("UPDATE 'update' SET type='" + UpdateTypeInput.SelectedValue + "',content='" + UpdateContentInput.Text + "',tip='" + UpdateTipInput.Text + "' WHERE id=" + UpdateId, connection);
      await updateCmd.ExecuteNonQueryAsync();
      await connection.CloseAsync();
      ContentDialog successDialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "提示",
        Content = "修改成功",
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await successDialog.ShowAsync();
      Back();
    }
    catch (Exception err)
    {
      ContentDialog dialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "错误",
        Content = err.Message,
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await dialog.ShowAsync();
    }
  }
  async void DeleteUpdate(object sender, RoutedEventArgs args)
  {
    if (sender is Button btn)
    {
      ContentDialog confirmDialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "提示",
        Content = "删除后无法恢复，确定删除？",
        PrimaryButtonText = "确定",
        CloseButtonText = "取消",
        DefaultButton = ContentDialogButton.Primary
      };
      var result = await confirmDialog.ShowAsync();
      if (result == ContentDialogResult.Primary)
      {
        var e = (UpdateItem)btn.Tag;
        var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
        await connection.OpenAsync();
        var deleteCmd = new SqliteCommand("DELETE FROM 'update' WHERE id=" + e.Id, connection);
        await deleteCmd.ExecuteNonQueryAsync();
        await connection.CloseAsync();
        ContentDialog successDialog = new()
        {
          XamlRoot = XamlRoot,
          Title = "提示",
          Content = "删除成功",
          PrimaryButtonText = "确定",
          DefaultButton = ContentDialogButton.Primary
        };
        await successDialog.ShowAsync();
        LoadList();
      }
    }
  }
}